import { setToken, getToken } from '@/utils/auth'
import { loginWxopenid } from '@/api/login'
import { getUserInfo } from '@/api/user'
import { Message } from '@/utils/wxUtil'
const userInfo = uni.getStorageSync('userInfo') || {
	store: {}
}
const state = {
	isLogin: !!getToken(),
	user: userInfo,
	showLogin: false
}

const mutations = {
  CHANGE_SETTING: (state, data) => {
    const keys = Object.keys(data)
    keys.forEach(key => {
      if (state.hasOwnProperty(key)) {
        state[key] = data[key]
      }
    })
  }
}

const actions = {
	getWxCode({ commit }) {
		return new Promise(async (resolve, reject) => {
			uni.login({
				success: async ({ code }) => {
					resolve(code)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	login({ commit }, wxopenid) {
		return new Promise(async (resolve, reject) => {
			Message.loading.show('登陆中…')
			try {
				const { data } = await loginWxopenid({ wxopenid }, { needLoading: false, needMsg: false })
				Message.loading.hide()
				setToken(`Bearer ${data.token}`)
				await actions.updateUserInfo({ commit })
				resolve(true)
			} catch {
				Message.loading.hide()
				resolve(false)
			}
		})
	},
	updateUserInfo({ commit }) {
		return new Promise((resolve, reject) => {
			getUserInfo({}, { needLoading: false }).then(({ data }) => {
				if (data.id) {
					commit('CHANGE_SETTING', {
						isLogin: true,
						user: data
					})
					uni.setStorageSync('userInfo', data)
					resolve(data)
				}
			}).catch(err => {
				reject(err)
			})
		})
	}
}

export default {
  state,
  mutations,
  actions
}
